package com.igd.utils.dev;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.igd.pojo.vo.dev.PageCreateData;
import com.igd.pojo.vo.dev.PageFieldData;
import com.igd.utils.CommonUtil;
import com.igd.utils.Dom4jUtil;

/**
 * @createDate 2013-6-29
 *
 * @author QIAOYU
 *
 * @version 1.0
 *
 * @description 页面创建工具类
 */

public class PageCreatUtil {
	
	private static PageCreatUtil pageUtil = null;
	
	private Dom4jUtil domUtil = Dom4jUtil.getInstance();
	
	/** 页面类型:数据修改页面类型 */
	private final String PAGE_TYPE_UPD = "update";
	
	/** 页面数据标签:Struts数据标签 */
	private final String PAGE_DATA_TAG_STRUTS = "struts";
	
	/** Struts数据标签获取值前缀 */
	private final String DATA_TAG_STRUTS_PREFIX = "#";
	
	private PageCreatUtil(){};
	
	public static PageCreatUtil getInstance(){
		
		if(pageUtil == null){
			
			synchronized (PageCreatUtil.class) {
				
				pageUtil = new PageCreatUtil();

			}
		}
		
		return pageUtil;
	}
	
	/**
	 * 创建HTML页面代码
	 * 
	 * @param page 创建页面所需的页面数据类
	 * 
	 * @return String
	 * 
	 * @throws DocumentException
	 */
	public String createPage(PageCreateData page) throws DocumentException{
		
		if(null != page && null != page.getPageField() && page.getPageField().size() > 0){
			
			String htmlCode = this.createPageHtmlCode(page);
				
			return htmlCode;

		}
		
		return null;
	}
	
	/**
	 * 根据模板创建页面代码
	 * 
	 * 
	 * @param page
	 * 
	 * @return
	 * 
	 * @throws DocumentException 
	 */
	private String createPageHtmlCode(PageCreateData page) throws DocumentException{
		
		if(null != page && page.getPageField().size() > 0){
			
			StringBuffer buffer = new StringBuffer();
			
			if(StringUtils.isNotEmpty(page.getPageLayout()) && StringUtils.isNotEmpty(page.getPageOpenType())){
				
				String templateName = page.getPageOpenType().concat(page.getPageLayout());
				
				Map<String,Element> fieldMap = this.initPageTemplate();
				
				Element pageEle = fieldMap.get(templateName);
				
				String open = pageEle.element("open").getText();
				
				String close = pageEle.element("close").getText();
				
				String forOpen = pageEle.element("forOpen").getText();
				
				String forClose = pageEle.element("forClose").getText();
				
				buffer.append(open);
				
				for(PageFieldData field:page.getPageField()){
					
					Element fieldEle = this.createFiled(field,page);
					
					String filedHtml = StringEscapeUtils.unescapeXml(fieldEle.asXML());
					
					buffer.append(forOpen.concat(filedHtml).concat(forClose));

				}
				
				buffer.append(close);
				
				return buffer.toString();
				
			}
		}
		
		return null;
	}
	
	/**
	 * 创建字段信息元素
	 * 
	 * @param field
	 * 
	 * @param page
	 * 
	 * @return
	 * 
	 * @throws DocumentException 
	 */
	private Element createFiled(PageFieldData field,PageCreateData page) throws DocumentException{
		
		Map<String,Element> fieldMap = this.initPageTemplate();
		
		String pageType = page.getPageType();
		
		String dataTag = page.getDataTag();
		
		String className = page.getClassName().substring(page.getClassName().lastIndexOf(".")+1,page.getClassName().length()).toLowerCase();
		
		String fieldName = field.getFieldName();
		
		String validType = field.getValidType();
		
		Element fieldEle = DocumentHelper.createDocument().addElement("");

		Element htmlEle = DocumentHelper.createDocument().addElement("");
		
		if(StringUtils.isNotEmpty(validType)){
			
			fieldEle = fieldMap.get(validType);
			
			if(null != fieldEle && fieldEle.elements().size() > 0){

				htmlEle = (Element) fieldEle.elements().get(0);
				
				String fieldDomNameVal = className.concat(".").concat(fieldName);
				
				domUtil.setAttributeVal(htmlEle,"name",fieldDomNameVal);
				
				domUtil.setAttributeVal(htmlEle,"id",fieldName);
				
				if(Boolean.valueOf(field.getIsRequired().toLowerCase())){
					
					String classValue = domUtil.getAttributeVal(htmlEle,"class");
					
					String newClassValue = null;
					
					if(StringUtils.isNotEmpty(classValue)){
						
						newClassValue = classValue.concat(" ").concat("required");
						
					}else{
						
						newClassValue = "required";
						
					}
					
					domUtil.setAttributeVal(htmlEle,"class",newClassValue);
					
				}
				
				/**判断是否生成数据修改页面*/
				if(pageType.equals(this.PAGE_TYPE_UPD)){
					
					if(dataTag.equals(this.PAGE_DATA_TAG_STRUTS)){
						
						Element tag = fieldMap.get(this.PAGE_DATA_TAG_STRUTS);
						
						String strutsTag = tag.getText().trim().replace("expression",DATA_TAG_STRUTS_PREFIX.concat(fieldDomNameVal));
						
						domUtil.setAttributeVal(htmlEle,"value",strutsTag.trim());
					}
				}
			}
		}
		
		return htmlEle;
	}
	
	/**
	 * 初始化页面模板信息
	 * 
	 * @return Map<String,Element>
	 * 
	 * @throws DocumentException
	 */
	private Map<String,Element> initPageTemplate() throws DocumentException{

		String templatePath = this.getTemplateFilePath();
		
		if(StringUtils.isNotEmpty(templatePath)){
			
			SAXReader reader = new SAXReader();
			
			Document doc = reader.read(new File(templatePath));
			
			if(null != doc){
				
				domUtil.setDoc(doc);
				
				Element root = domUtil.getRoot();
				
				@SuppressWarnings("unchecked")
				List<Element> list = root.elements();
				
				if(null != list && list.size()>0){
					
					HashMap<String,Element> map = new HashMap<String,Element>(list.size());
					
					for(Element e:list){
						
						String pageId = e.attribute("id").getValue();
						
						map.put(pageId, e);

					}
					
					return map;
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 获取模板文件路径
	 * 
	 * @return
	 */
	private String getTemplateFilePath(){
		
		String fileName = "igd.template.xml";
		
		return CommonUtil.getClassPathFile(fileName);

	}
}
